package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.entity.*;
import com.itheima.service.CategoryService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Auther: 宋H
 * @Date: 2022/9/9
 * @Description: com.itheima.controller
 * @version: 1.0
 */
@RestController
@Slf4j
@RequestMapping("/setmeal")
@Api(tags="套餐相关接口")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * @CacheEvict 清除缓存
     * allEntries属性将这个缓存中的数据都删除
     * 新增套餐信息
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmeal",allEntries = true)
    @PostMapping
    @ApiOperation("新增套餐接口")
    public R<String> setmealSave(@RequestBody SetmealDto setmealDto){
        log.info(setmealDto.toString());
        setmealService.setmealDishSave(setmealDto);
        return R.success("套餐数据保存成功");
    }

    @GetMapping("/page")
    @ApiOperation("套餐分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name="page",value="需要查询第几页",required = true),
            @ApiImplicitParam(name="pageSize",value="每页查询几行",required = true),
            @ApiImplicitParam(name="name",value="套餐的名称",required = false),
    })
    public R<Page> setmealSave(int page, int pageSize, String name){
        log.info("分页信息查询中,当前第{}页,每页查询{}个",page,pageSize);
        Page<Setmeal> pageInfo=new Page<>(page,pageSize);
        Page<SetmealDto> setmealDtoPage=new Page<>();

        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.like(name!=null,Setmeal::getName,name).orderByAsc(Setmeal::getUpdateTime);
        setmealService.page(pageInfo,lqw);

        //对象的拷贝
        BeanUtils.copyProperties(pageInfo,setmealDtoPage,"records");
        List<Setmeal> records = pageInfo.getRecords();

       List<SetmealDto> list = records.stream().map((item)->{
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item,setmealDto);//此时SetmealDto为空需把records赋给它

            Long categoryId = item.getCategoryId();
           Category category = categoryService.getById(categoryId);
           if(category!=null){
                setmealDto.setCategoryName(category.getName());//通过分类名称设置SetmealDto对象的setCategoryName（套餐分类名称）
            }
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDtoPage.setRecords(list);//之前对象拷贝没有拷贝它

        return R.success(setmealDtoPage);
    }

    /**
     * 根据id删除套餐信息
     * @param ids
     * @return
     */
    @ApiOperation("删除套餐信息接口")
    @DeleteMapping
    public R<String> setmealDelete(@RequestParam("ids") List<Long> ids){
        log.info("删除套餐id,{}",ids);
        //首先删除套餐信息
        setmealService.setmealRemove(ids);
        //在删除套餐对应的菜品信息
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getDishId,ids);
        setmealDishService.remove(lqw);
        return R.success("套餐及其对应菜品信息删除成功");
    }

    /**
     * 更改套餐的售卖状态（单个或批量）
     * @param status
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmeal",allEntries = true)
    @PostMapping("/status/{status}")
    @ApiOperation("更改套餐的售卖状态接口")
    public R<String> setmealStatus(@PathVariable("status") Integer status,@RequestParam List<Long> ids){
        log.info("状态,{}",status);
        log.info("修改菜品,{}",ids);
        setmealService.setmealStatus(status,ids);

        return R.success("套餐售卖状态以更改");
    }

    /**
     * 通过ID查询套餐信息和对应的菜品信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("通过ID查询套餐信息接口")
    public R<SetmealDto> setmealGetById(@PathVariable Long id){
        log.info("正在查询套餐ID,{}",id);
        SetmealDto setmealDto = setmealService.getSetmealById(id);

        return R.success(setmealDto);
    }

    /**
     * 修改套餐信息
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmeal",allEntries = true)
    @PutMapping
    @ApiOperation("修改套餐信息接口")
    public R<String> setmealUpdate(@RequestBody SetmealDto setmealDto){
        log.info(setmealDto.toString());
        setmealService.setmealUpdate(setmealDto);
        return R.success("修改套餐信息成功");
    }

    /**
     * @Cacheable启用缓存
     * 将方法的运行结果进行缓存，以后再要相同数据，直接从缓存中获取，不用调用方法
     * 查询套餐信息
     * cacheNames/value ：用来指定缓存组件的名字
     * key ：缓存数据时使用的 key，可以用它来指定。默认是使用方法参数的值
     * @param setmeal
     * @return
     */
    @Cacheable(value = "setmeal",key = "#setmeal.categoryId+'_'+#setmeal.status")
    @GetMapping("/list")
    @ApiOperation("查询套餐信息接口")
    public R<List<Setmeal>> setmealList(Setmeal setmeal){
        log.info("正在查询套餐信息中",setmeal.toString());
        List<Setmeal> setmealList;
        String setmealKey="setmeal_"+setmeal.getCategoryId()+"_"+setmeal.getStatus();

        setmealList = (List<Setmeal>) redisTemplate.opsForValue().get(setmealKey);
        if(setmealList!=null){
            R.success(setmealList);
        }else{
            LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
            lqw.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
            lqw.eq(Setmeal::getStatus,setmeal.getStatus()).orderByDesc(Setmeal::getUpdateTime);
            setmealList = setmealService.list(lqw);
            redisTemplate.opsForValue().set(setmealKey,setmealList);
        }
        return R.success(setmealList);
    }

}
